#!/bin/bash
# stupid zip doesn't support stdin with file name, so we have to use file
# sed replace src:, may be too many. better way is src within font-face
nook() {
  unzip -o "$1" OPS/css/main.css
  sed -i -e "s_src:_src:url(res:///system/fonts/DroidSansFallback.ttf),_" OPS/css/main.css
  zip "$1" OPS/css/main.css
}

dld_sc() {
  echo $1
  curl -# -L -A Stanza -C - "http://www.shucang.com/s/bookService.php?vk=$1" -o "dled/$1.epub"
}

dld_cn() {
  #curl -L -A Stanza -u ai9 "http://www.cnepub.com/online_catalog/user_authorize.php?id=$1" -o $1.epub
  echo $1 #URL like http://www.cnepub.com/122306.html
  btitle=`curl -s "$1"|grep -o "<h1>[^<]*"|cut -d'>' -f2|tr ' ' '_'`
  btitle2=`python -c "import urllib; print urllib.quote('''$btitle''')"`
  bid=`echo $1|grep -o "[0-9]\+"`
  bid1=$((bid/10000))
  [ $bid1 -lt 10 ] && bid1="0$bid1"
  curl -# -C - -A Stanza "http://www.cnepub.com/bookfiles/000/$bid1/${bid: -4:2}/${bid: -2:2}/$btitle2.epub" -o "$btitle.epub"
  echo $bid $btitle >> cnepub.dled
}

newbooks() {
  uid=${1:-5976}
  last=`head -n 1 $uid.books|cut -d' ' -f 1`
  PAGE=`curl -s -L -A iPhone "http://www.shucang.com/m/members.php?UID=$uid"|grep -m 1 -B 999 $last`
  books=`echo "$PAGE"|grep btitle|cut -d= -f4|cut -d'<' -f1|tr '">' ' '`
  [ -z "$books" ] && { echo No new books; return 0; }
  echo "$books"
  echo "Start downloading:"
  echo "$books"|tac|while read bid btitle;do
    dld_sc $bid && sed -i "1i$bid  $btitle" $uid.books
  done
}
